import numpy as np
import numpy.fft as fft
import matplotlib
matplotlib.use(backend="TkAgg")
import matplotlib.pyplot as plt

def test_fftfreq():
    """
    return the discrete Fourier transform sample frequencies

    the return float array 'f' contains the frequency bin centers in cycles
    per unit of the sample spacing (with 0 at the start).For instance, if the
    sample spacing is in seconds, then the frequency unit is cycles/second.

    Given a window length 'n' and a sample spacing 'd':
    f=[0,1,..., n/2-1,  -n/2, ..., -1]/(d*n) if n is even
    f=[0,1,..., (n-1)/2, -(n-1)/2,...-1]/(d*n) if n is odd
    :return:
    """
    # 构造一个信号：2Hz+5Hz
    fs=50 # 采样频率 50Hz
    t = np.arange(0,1,1/fs) # 1秒时间
    x = np.sin(2*np.pi*2*t) + 0.5*np.sin(2*np.pi*5*t)

    #FFT
    X = fft.fft(x)
    freqs = fft.fftfreq(len(x), d=1/fs)

    # 只绘正频率部分
    idx = freqs>=0
    plt.plot(freqs[idx], np.abs(X)[idx])
    plt.xlabel("Frequency (Hz)")
    plt.ylabel("Amplitude")
    plt.title("Frequency Spectrum")
    plt.show()


def test_sign():
    '''
    returns -1 if x<0, 0 if x==0, 1 if x>0
    for complex numbers, x/|x|
    :return:
    '''
    print(np.sign([-5, 4.5]))
    print(np.sign(0))
    print(np.sign([3-4j, 8j]))


if __name__ == '__main__':
    # test_fftfreq()
    test_sign()